import { $http } from '@/api/index';
import { ElMessage } from 'element-plus';

class Loader {
    timer: any;
    isReady: boolean; // 该资源服务端是否已经准备好
    isLoaded: boolean; // 该资源是否在客户端下载完成
    resCheckApiUrl: string; // 检测正在下载的资源状况的 url
    realUrl = ''; // 资源准备好后的真实地址
    onDownload: (res: string) => void; // 下载完成事件
    constructor(_resCheckUrl: string, onLoadFinished: (res: string) => void, public interval?: number) {
        this.isLoaded = false;
        this.isReady = false;
        this.interval = interval ? interval : 2000;
        this.resCheckApiUrl = _resCheckUrl;
        this.onDownload = onLoadFinished;
    }
    startLoad() {
        this.timer = setInterval(() => {
            if (this.isReady) {
                clearInterval(this.timer);
            }
            this.checkDownLoad();
        }, this.interval);
    }

    async checkDownLoad() {
        if (this.isReady) {
            return;
        }
        const { loadState, realResUrl, error } = await $http.get('/saas/' + this.resCheckApiUrl);
        console.log(loadState, realResUrl, error);
        // 服务器准备完毕
        if (loadState === 1) {
            this.isReady = true; // 清定时器
            this.downLoad(realResUrl);
        } else if (loadState === 2) {
            // 资源准备失败
            ElMessage.error('服务端资源生成失败');
            this.isReady = true; // 清定时器
        }
    }

    private downLoad(url: string, fileName = 'loadfile') {
        if (!url) {
            return;
        }
        this.realUrl = url;
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        // document.body.appendChild(link);
        link.click(); // 强制触发a标签事件
        //  document.body.removeChild(link);

        // 这里其实真正才开始下载 并没有下载完成
        this.isLoaded = true;
        if (this.onDownload) {
            this.onDownload(this.realUrl);
        }
    }
}

// 异步下载管理器 配合服务端异步生成资源
export default class DownLoadMgr {
    // 单例
    private static _instance = new DownLoadMgr();
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    private constructor() {}

    public static get Instance() {
        return DownLoadMgr._instance;
    }

    LoaderList: Loader[] = []; // 正在下载的loader list

    isLoading(api: string) {
        return this.LoaderList.some((loader) => {
            return loader.resCheckApiUrl === api;
        });
    }

    download(resApiUrl: string) {
        if (this.isLoading(resApiUrl)) {
            ElMessage.warning('当前资源正在后台下载中..');
            return;
        }

        const loader = new Loader(resApiUrl, (res) => {
            console.log('资源下载完成', res);
            ElMessage.success('资源下载完成');
            this.LoaderList.filter((loader) => {
                return loader.resCheckApiUrl !== resApiUrl;
            }); // 下载完成之后 从正在下载的 list 移除
        });
        loader.startLoad();
        this.LoaderList.push(loader);
    }
}
